//
//  ZCScanVC.m
//  zctx
//
//  Created by ZhengDarren on 15/9/28.
//  Copyright © 2015年 sanliang. All rights reserved.
//
#import "QRCodeReaderView.h"
#import "ZCScanInputVC.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import "ZCScanVC.h"
#import "ZCSearchVC.h"


#import "ZCScanDeatailsMoreVC.h"
#define widthRate SCREEN_WIDTH/320
#define IOS8 ([[UIDevice currentDevice].systemVersion intValue] >= 8 ? YES : NO)
@interface ZCScanVC ()<QRCodeReaderViewDelegate,UIAlertViewDelegate,AVCaptureMetadataOutputObjectsDelegate>{
    QRCodeReaderView * readview;//二维码扫描对象
    
    BOOL isFirst;//第一次进入该页面
    BOOL isPush;//跳转到下一级页面
}
@property BOOL isconnect;
@property (strong, nonatomic) CIDetector *detector;

@property (nonatomic,strong)NSString *barStr;
@end

@implementation ZCScanVC

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"ZCScanVC"];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"扫描食品条形码";
    [self initnavegation];
    self.view.backgroundColor = [UIColor whiteColor];
    self.isconnect = YES;
    isFirst = YES;
    isPush = NO;
    
//    [self accordingQcode:@"6927849460601"];
    
    [self InitScan];
    [self addOther];//输入条形码
    
}

#pragma mark 导航栏
-(void)initnavegation{
    
    UIButton * leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 19, 36);
    [leftButton setImage:[UIImage imageNamed:@"navigation_back"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * barButtonItem_leftNavBar = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.leftBarButtonItem = barButtonItem_leftNavBar;
}
#pragma mark 输入条形码
-(void)addOther{
    
    //开关灯button
    UIButton * turnBtn = [[UIButton alloc]init];
    turnBtn.backgroundColor = [UIColor blackColor];
    turnBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [turnBtn setTitle:@"输入条码" forState:UIControlStateNormal];
    [turnBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [turnBtn setImage:[UIImage imageNamed:@"scan_input"] forState:UIControlStateNormal];
    turnBtn.layer.cornerRadius = 45*widthRate/2;
    
    if (IS_IPHONE_4_OR_LESS) {
        turnBtn.frame=CGRectMake((SCREEN_WIDTH-100*widthRate)/2, (SCREEN_HEIGHT-80*widthRate), 100*widthRate, 45*widthRate);
    }else if(IS_IPHONE_5){
        turnBtn.frame=CGRectMake((SCREEN_WIDTH-100*widthRate)/2, (SCREEN_HEIGHT-100*widthRate), 100*widthRate, 45*widthRate);
    }else{
        turnBtn.frame=CGRectMake((SCREEN_WIDTH-100*widthRate)/2, (SCREEN_HEIGHT-120*widthRate), 100*widthRate, 45*widthRate);
    }
   
    [turnBtn addTarget:self action:@selector(turnBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:turnBtn];
}

-(void)turnBtnEvent:(UIButton *)sender{
    NSLog(@"sd");
    //毛玻璃效果
//    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
//    UIVisualEffectView *effectview = [[UIVisualEffectView alloc] initWithEffect:blur];
//    effectview.frame = self.view.bounds;
//    [self.view addSubview:effectview];
    
    ZCScanInputVC *input = [[ZCScanInputVC alloc]init];
    input.raiseStr = self.israise;
    input.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:input animated:NO];
//    input.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
//    [self presentViewController:input animated:YES completion:^{
//        
//    }];
}

-(void)backButtonPressed{
    if ([self.israise isEqualToString:@"raise"]) {
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    } 
}

#pragma mark 初始化扫描
- (void)InitScan
{
    if (readview) {
        [readview removeFromSuperview];
        readview = nil;
    }
    
    readview = [[QRCodeReaderView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    readview.is_AnmotionFinished = YES;
    readview.backgroundColor = [UIColor clearColor];
    readview.delegate = self;
    readview.alpha = 0;
    
    [self.view addSubview:readview];
    
    [UIView animateWithDuration:1 animations:^{
        readview.alpha = 1;
    }completion:^(BOOL finished) {
        
    }];

}

#pragma mark -显示网络状态
-(void)showReachability{
    NSLog(@"无网络 ->显示");
    self.isconnect = NO;
    readview.connectLable.hidden = NO;
    readview.readLineView.hidden = YES;
}
- (void)hideReachability{
    NSLog(@"有网络 ->隐藏");
    self.isconnect = YES;
    readview.connectLable.hidden = YES;
    readview.readLineView.hidden = NO;
}

#pragma mark -QRCodeReaderViewDelegate
- (void)readerScanResult:(NSString *)result
{

    if (self.isconnect ==YES) {
        readview.is_Anmotion = YES;
        [readview stop];
        
        //播放扫描二维码的声音
        SystemSoundID soundID;
        NSString *strSoundFile = [[NSBundle mainBundle] pathForResource:@"noticeMusic" ofType:@"wav"];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:strSoundFile],&soundID);
        AudioServicesPlaySystemSound(soundID);
        self.barStr = result;
        [self accordingQcode:result];
    }
    
//    [self performSelector:@selector(reStartScan) withObject:nil afterDelay:1.5];
}

#pragma mark - 扫描结果处理
- (void)accordingQcode:(NSString *)str
{
    
    [NetworkManager requestProductGetInfoByBarcodeWithMid:UserModel.mid barcode:str pagecount:@"0" success:^(NSDictionary *dictResponse) {
        
        NSLog(@"sdfs");
        NSObject *array = (NSObject *)[dictResponse objectForKey:@"content"];
        
        NSDictionary *more_dataDict = (NSDictionary *)[dictResponse objectForKey:@"more_data"];
        
        NSDictionary *more_faqDict = (NSDictionary *)[more_dataDict objectForKey:@"faq"];
        
        NSDictionary *more_buyDict = (NSDictionary *)[more_dataDict objectForKey:@"how_to_buy"];
    
        if ([array isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dict =(NSDictionary *)array;
            if (dict.count>0) {
                if ([self.israise isEqualToString:@"raise"]) {
                    NSString *strname = [dict objectForKey:@"name"];
                    self.ScanResultWithName(strname);
                    [self.navigationController popViewControllerAnimated:YES];
                }else{
                    [self gotoScanDeatailsMore:dict andf:more_faqDict andb:more_buyDict];
                }
            }else{
                 NSLog(@"22222");
                [self gotoScanDeatailsMore:nil andf:more_faqDict andb:more_buyDict];
            }
        }else{
             NSLog(@"33333暂无该条码信息");
            [[[iToast makeText:@"暂无该条码信息"]setGravity:iToastGravityCenter] show];
            if (readview) {
                [self reStartScan];
            }
        }
        
    } failure:^(NSError *error) {
        NSLog(@"网络出错");
        if (readview) {
            [self reStartScan];
        }
    }];
}

-(void)gotoScanDeatailsMore:(NSDictionary *)barDictionary andf:(NSDictionary *)fDictionary andb:(NSDictionary *)buyDictionary{
    
    ZCScanDeatailsMoreVC *vc = [[ZCScanDeatailsMoreVC alloc]init];
    vc.barcodeDictionary = barDictionary;
    vc.faqDictionary = fDictionary;
    vc.buyDictionary = buyDictionary;
    vc.barcodeStr = self.barStr;
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:NO];
}


//每次扫描完后。继续扫描
- (void)reStartScan
{
    readview.is_Anmotion = NO;
    
    if (readview.is_AnmotionFinished) {
        [readview loopDrawLine];
    }
    [readview start];
}

#pragma mark - view
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"ZCScanVC"];
    [MTA trackPageViewBegin:@"ZCScanVC"];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    
//    if (isFirst || isPush) {
        if (readview) {
            [self reStartScan];
        }
//    }
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [MobClick endLogPageView:@"ZCScanVC"];
    [MTA trackPageViewEnd:@"ZCScanVC"];
    
    if (readview) {
        [readview stop];
        readview.is_Anmotion = YES;
    }
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (isFirst) {
        isFirst = NO;
    }
    if (isPush) {
        isPush = NO;
    }
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [readview start];
}

//            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"此条码暂时没有数据!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//            [alertView show];

@end
